package com.scgri.utils;

import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class ExcelUtil {

    public static void exportExcel(List<Map> list,File outputStream)
            throws Exception {

        HSSFWorkbook workbook = new HSSFWorkbook();
        HashSet<String> sets = new HashSet<>();
        for (Map map : list) {
            for (Object o : map.keySet()) {
                sets.add(o.toString());
            }
        }
        Object[] key = sets.toArray();
        int rowNum = 1;
        HSSFSheet sheet = null;
        sheet = workbook.createSheet();//默认名称 “sheet0”
        HSSFRow row = sheet.createRow(0);//设置第一行所有标题字段
        for (int i = 0; i < key.length; i++) {
            try {
                row.createCell(i).setCellValue(new HSSFRichTextString(key[i].toString()));
            }catch (NullPointerException e){
                row.createCell(i).setCellValue(new HSSFRichTextString(""));
                e.printStackTrace();
            }
        }
        for (Map map : list) {
            HSSFRow row1 = sheet.createRow(rowNum);
            for (int i = 0; i < key.length; i++) {
                try {
                    row1.createCell(i).setCellValue(map.get(key[i]).toString());
                }catch (NullPointerException e){
                    row.createCell(i).setCellValue("");
                    e.printStackTrace();
                }
            }
            rowNum++;
        }
        workbook.write(outputStream);
        workbook.close();
    }
}


